package net.seehope.foodie.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.seehope.foodie.exception.PassportException;
import net.seehope.foodie.mapper.UsersMapper;
import net.seehope.foodie.pojo.Users;
import net.seehope.foodie.pojo.bo.UserBO;
import net.seehope.foodie.pojo.vo.UserInfoVo;
import net.seehope.foodie.pojo.vo.UsernameIsExistVo;
import net.seehope.foodie.properties.ProjectProperties;
import net.seehope.foodie.service.RegisterService;

@Service
public class RegisterImpl implements RegisterService {

	@Autowired 
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private UsersMapper usersMapper;
	
	@Autowired
	private Sid sid;
	
	@Autowired
	private ProjectProperties projectProperties;
	
	@Override
	public void renderusernameIsExist(String username) {
	
		Users users = new Users();
		users.setUsername(username);
		List<Users> list = usersMapper.select(users);
		
		if(list.size()!=0) {
			throw new PassportException("用户名已存在，请重新输入");
		}
		
	}

	@Transactional
	@Override
	public void regist(UserBO userBO) throws ParseException {
		renderusernameIsExist(userBO.getUsername());
		
		if(!StringUtils.equals(userBO.getPassword(),userBO.getConfirmPassword())) {
			throw new PassportException("用户两次输入密码不一致，请重新输入");
		}
		
		Users users = new Users();
		//生成sid
		users.setId(sid.nextShort());
		users.setUsername(userBO.getUsername());
		//加密的密码
		users.setPassword(passwordEncoder.encode(userBO.getPassword()));
		users.setFace(projectProperties.getUserDefaultFace());
		users.setNickname(null);
		users.setCreatedTime(new Date());
		users.setUpdatedTime(new Date());
		//插入数据库
		usersMapper.insert(users);
		
	}

	@Override
	public Users login(UserBO userBO) {
		Users users = new Users();
		users.setUsername(userBO.getUsername());
		users.setPassword(passwordEncoder.encode(userBO.getPassword()));
		Users loginUsers = usersMapper.selectOne(users);
		
		if(loginUsers==null) {
			throw new PassportException("用户名或密码错误");
		}
		
		if(!passwordEncoder.matches(userBO.getPassword(),loginUsers.getPassword())) {
			throw new PassportException("用户名或密码错误");
		}
		
		return loginUsers;
	}

}
